package com.MutiModule.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public final class JdbcUtil {
	private static Properties dbProperties = new Properties();

	private static final Log LOGGER = LogFactory.getLog(JdbcUtil.class);

	public static Properties getDbProperties() {
		if (dbProperties.isEmpty()) {
			InputStream is = JdbcUtil.class.getResourceAsStream("/jdbc.properties");
			BufferedReader bf;
			try {
				bf = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				try {
					dbProperties.load(bf);
					if (dbProperties.containsKey("connection.driver_class")) {
						if (LOGGER.isDebugEnabled()) {
							LOGGER.debug("dbProperties:");
							for (Entry<Object, Object> entry : dbProperties.entrySet()) {
								LOGGER.debug("  " + entry.getKey() + " = " + entry.getValue());
							}
						}
					} else {
						LOGGER.warn("connection.driver_class not in Classpath!");
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}

		return dbProperties;
	}

	public static Connection getConnection() throws ClassNotFoundException, SQLException {
		getDbProperties();

		String driverClassName = dbProperties.getProperty("connection.driver_class");
		String connectUrl = dbProperties.getProperty("connection.url");
		String user = dbProperties.getProperty("connection.username");
		String pwd = dbProperties.getProperty("connection.password");

		Class.forName(driverClassName);

		Properties prop = new Properties();
		if (user != null) {
			prop.setProperty("user", user);
		}
		if (pwd != null) {
			prop.setProperty("password", pwd);
		}

		return DriverManager.getConnection(connectUrl, prop);
	}

	private JdbcUtil() {
		
	}
}
